<template>
  <view class="venue-container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="header-content">
        <text class="header-title">场地管理</text>
        <view class="header-actions">
          <uni-icons type="settings" size="20" color="#fff" @click="handleSettings" />
        </view>
      </view>
    </view>

    <!-- 门店信息概览卡片 -->
    <view class="overview-section" v-if="storeInfo">
      <view class="overview-card">
        <view class="store-info-header">
          <text class="store-name">{{ storeInfo.name }}</text>
          <text class="store-address">{{ storeInfo.address }}</text>
        </view>
        <view class="store-stats">
          <view class="overview-item">
            <text class="overview-value">{{ venueList.length }}</text>
            <text class="overview-label">场地总数</text>
          </view>
          <view class="overview-item">
            <text class="overview-value">{{ availableCount }}</text>
            <text class="overview-label">可用</text>
          </view>
          <view class="overview-item">
            <text class="overview-value">{{ busyCount }}</text>
            <text class="overview-label">使用中</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 功能模块网格 -->
    <view class="modules-section">
      <view class="modules-grid">
        <view 
          class="module-card" 
          v-for="module in modules" 
          :key="module.key"
          @click="navigateToModule(module)"
        >
          <view class="module-icon">
            <uni-icons :type="module.icon" size="32" :color="module.color" />
          </view>
          <text class="module-title">{{ module.title }}</text>
          <text class="module-desc">{{ module.desc }}</text>
          <view class="module-badge" v-if="module.badge">
            <text class="badge-text">{{ module.badge }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 快捷操作区 -->
    <view class="quick-actions">
      <text class="section-title">快捷操作</text>
      <scroll-view class="actions-scroll" scroll-x>
        <view class="actions-list">
          <view class="action-item" @click="navigateToDetail()">
            <view class="action-icon">
              <uni-icons type="plus" size="24" color="#1890FF" />
            </view>
            <text class="action-text">新增场地</text>
          </view>
          <view class="action-item" @click="handleBatchOperation">
            <view class="action-icon">
              <uni-icons type="checkbox" size="24" color="#1890FF" />
            </view>
            <text class="action-text">批量操作</text>
          </view>
          <view class="action-item" @click="handleStatusManage">
            <view class="action-icon">
              <uni-icons type="gear" size="24" color="#1890FF" />
            </view>
            <text class="action-text">状态管理</text>
          </view>
          <view class="action-item" @click="handleDataExport">
            <view class="action-icon">
              <uni-icons type="download" size="24" color="#1890FF" />
            </view>
            <text class="action-text">数据导出</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 筛选栏 -->
    <view class="filter-section">
      <text class="section-title">状态筛选</text>
      <view class="filter-card">
        <scroll-view scroll-x class="filter-scroll">
          <view class="filter-tags">
            <view 
              class="filter-tag" 
              :class="{ active: queryParams.status === undefined }"
              @click="handleStatusFilter(undefined)"
            >
              全部
            </view>
            <view 
              class="filter-tag" 
              :class="{ active: queryParams.status === 1 }"
              @click="handleStatusFilter(1)"
            >
              空闲中
            </view>
            <view 
              class="filter-tag" 
              :class="{ active: queryParams.status === 2 }"
              @click="handleStatusFilter(2)"
            >
              使用中
            </view>
            <view 
              class="filter-tag" 
              :class="{ active: queryParams.status === 3 }"
              @click="handleStatusFilter(3)"
            >
              保洁中
            </view>
            <view 
              class="filter-tag" 
              :class="{ active: queryParams.status === 5 }"
              @click="handleStatusFilter(5)"
            >
              维护中
            </view>
          </view>
        </scroll-view>
      </view>
    </view>

    <!-- 场地列表 -->
    <view class="venue-list-section">
      <text class="section-title">场地列表</text>
      <scroll-view
        scroll-y
        class="venue-list-scroll"
        refresher-enabled
        @refresherrefresh="handleRefresh"
        :refresher-triggered="isRefreshing"
        @scrolltolower="handleLoadMore"
      >
        <view v-if="venueList.length > 0" class="venue-list">
          <view
            class="venue-card"
            v-for="venue in venueList"
            :key="venue.id"
            @click="navigateToDetail(venue.id)"
          >
            <view class="venue-header">
              <view class="venue-info">
                <text class="venue-name">{{ venue.name }}</text>
                <text class="venue-type">{{ venue.venue_type }}</text>
              </view>
              <view class="venue-status">
                <uni-tag 
                  :text="getStatusText(venue.status)" 
                  :type="getStatusType(venue.status)" 
                  size="small" 
                />
              </view>
            </view>
            
            <view class="venue-details">
              <view class="detail-row">
                <view class="detail-item">
                  <uni-icons type="person" size="14" color="#999"></uni-icons>
                  <text class="detail-text">{{ venue.capacity }}人</text>
                </view>
                <view class="detail-item">
                  <uni-icons type="home" size="14" color="#999"></uni-icons>
                  <text class="detail-text">{{ venue.area }}㎡</text>
                </view>
                <view class="detail-item">
                  <uni-icons type="wallet" size="14" color="#999"></uni-icons>
                  <text class="detail-text">¥{{ venue.hour_price }}/时</text>
                </view>
              </view>
              
              <view class="detail-row" v-if="venue.facilities">
                <view class="facilities">
                  <uni-icons type="gear" size="14" color="#999"></uni-icons>
                  <view class="facility-tags">
                    <text 
                      v-for="(facility, index) in parseFacilities(venue.facilities)" 
                      :key="index"
                      class="facility-tag"
                    >
                      {{ facility }}
                    </text>
                  </view>
                </view>
              </view>
            </view>

            <view class="venue-actions" @click.stop>
              <button 
                class="action-btn primary" 
                @click="handleQuickBook(venue)"
                :disabled="venue.status !== 1"
              >
                {{ venue.status === 1 ? '快速预订' : '不可预订' }}
              </button>
              <button class="action-btn secondary" @click="showActionSheet(venue)">
                更多
              </button>
            </view>
          </view>
        </view>
        
        <uni-load-more v-if="venueList.length > 0 || loading" :status="loadingStatus"></uni-load-more>
        
        <view v-if="venueList.length === 0 && !loading" class="empty-container">
          <uni-icons type="home" size="60" color="#999"></uni-icons>
          <text class="empty-text">暂无场地</text>
          <button class="add-venue-btn" @click="navigateToDetail()">添加场地</button>
        </view>
      </scroll-view>
    </view>

    <!-- 状态切换弹窗 -->
    <uni-popup ref="statusPopup" type="bottom">
      <view class="status-modal">
        <view class="modal-header">
          <text class="modal-title">切换场地状态</text>
          <uni-icons type="close" size="20" @click="closeStatusModal"></uni-icons>
        </view>
        <view class="status-options">
          <view 
            v-for="status in statusOptions" 
            :key="status.value"
            class="status-option"
            @click="changeVenueStatus(status.value)"
          >
            <uni-tag :text="status.text" :type="status.type" size="small" />
            <text class="status-desc">{{ status.desc }}</text>
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { fetchVenues, fetchStoreDetail, updateVenue } from '@/api/store';
import type { Venue, VenueQuery, Store } from '@/types/store';

const venueList = ref<Venue[]>([]);
const storeInfo = ref<Store | null>(null);
const queryParams = reactive<VenueQuery>({
  page: 1,
  pageSize: 10,
  store_id: undefined,
});

const loading = ref(false);
const isRefreshing = ref(false);
const hasMore = ref(true);
const statusPopup = ref<any>(null);
const currentVenue = ref<Venue | null>(null);

const storeId = ref<number | null>(null);

const loadingStatus = computed(() => {
  if (loading.value) return 'loading';
  return hasMore.value ? 'more' : 'noMore';
});

// 计算可用场地数量
const availableCount = computed(() => {
  return venueList.value.filter(venue => venue.status === 1).length;
});

// 计算使用中场地数量
const busyCount = computed(() => {
  return venueList.value.filter(venue => venue.status === 2).length;
});

// 功能模块配置
const modules = ref([
  {
    key: 'available',
    title: '空闲场地',
    desc: '可预订场地',
    icon: 'checkmarkempty',
    color: '#52C41A',
    badge: availableCount.value > 0 ? availableCount.value.toString() : '',
  },
  {
    key: 'busy',
    title: '使用中',
    desc: '正在使用',
    icon: 'clock',
    color: '#1890FF',
    badge: busyCount.value > 0 ? busyCount.value.toString() : '',
  },
  {
    key: 'maintenance',
    title: '维护管理',
    desc: '维护保洁',
    icon: 'gear',
    color: '#FA8C16',
    badge: '',
  },
  {
    key: 'statistics',
    title: '使用统计',
    desc: '数据分析',
    icon: 'bars',
    color: '#722ED1',
    badge: '',
  },
]);

// 状态选项
const statusOptions = [
  { value: 1, text: '空闲中', type: 'success', desc: '场地可正常使用' },
  { value: 2, text: '使用中', type: 'primary', desc: '场地正在被使用' },
  { value: 3, text: '保洁中', type: 'warning', desc: '场地正在保洁' },
  { value: 4, text: '待保洁', type: 'default', desc: '场地需要保洁' },
  { value: 5, text: '维护中', type: 'error', desc: '场地正在维护' },
];

// 获取状态文本
const getStatusText = (status: number) => {
  const option = statusOptions.find(opt => opt.value === status);
  return option ? option.text : '未知';
};

// 获取状态类型
const getStatusType = (status: number) => {
  const option = statusOptions.find(opt => opt.value === status);
  return option ? option.type : 'default';
};

// 解析设施
const parseFacilities = (facilities: string) => {
  try {
    const parsed = JSON.parse(facilities);
    return Array.isArray(parsed) ? parsed.slice(0, 3) : [];
  } catch (error) {
    return [];
  }
};

// 获取场地列表
const getVenueList = async (isRefresh = false) => {
  if (loading.value) return;
  loading.value = true;

  if (isRefresh) {
    queryParams.page = 1;
  }

  try {
    const res = await fetchVenues(queryParams);
    if (isRefresh) {
      venueList.value = res.list;
    } else {
      venueList.value = [...venueList.value, ...res.list];
    }
    hasMore.value = venueList.value.length < res.total;
    
    if (queryParams.page) {
      queryParams.page++;
    } else {
      queryParams.page = 2;
    }
  } catch (error) {
    console.error('获取场地列表失败:', error);
    uni.showToast({ title: '获取场地列表失败', icon: 'none' });
  } finally {
    loading.value = false;
    isRefreshing.value = false;
  }
};

// 获取门店信息
const getStoreInfo = async () => {
  if (!storeId.value) return;
  
  try {
    const res = await fetchStoreDetail(storeId.value);
    storeInfo.value = res;
  } catch (error) {
    console.error('获取门店信息失败:', error);
  }
};

const handleRefresh = () => {
  isRefreshing.value = true;
  getVenueList(true);
};

const handleLoadMore = () => {
  if (hasMore.value && !loading.value) {
    getVenueList();
  }
};

const handleStatusFilter = (status: number | undefined) => {
  queryParams.status = status;
  getVenueList(true);
};

const navigateToDetail = (id?: number) => {
  const url = id 
    ? `/pages/venues/detail?id=${id}&storeId=${storeId.value}` 
    : `/pages/venues/detail?storeId=${storeId.value}`;
  uni.navigateTo({ url });
};

// 导航到模块页面
const navigateToModule = (module: any) => {
  switch (module.key) {
    case 'available':
      queryParams.status = 1;
      getVenueList(true);
      break;
    case 'busy':
      queryParams.status = 2;
      getVenueList(true);
      break;
    case 'maintenance':
      uni.showToast({ title: '维护管理功能开发中', icon: 'none' });
      break;
    case 'statistics':
      uni.showToast({ title: '统计功能开发中', icon: 'none' });
      break;
  }
};

// 快速预订
const handleQuickBook = (venue: Venue) => {
  uni.navigateTo({ 
    url: `/pages/bookings/create?venueId=${venue.id}&storeId=${storeId.value}` 
  });
};

// 显示操作菜单
const showActionSheet = (venue: Venue) => {
  currentVenue.value = venue;
  uni.showActionSheet({
    itemList: ['查看详情', '编辑场地', '切换状态', '预订管理', '删除场地'],
    success: (res) => {
      switch (res.tapIndex) {
        case 0:
          navigateToDetail(venue.id);
          break;
        case 1:
          navigateToDetail(venue.id);
          break;
        case 2:
          statusPopup.value?.open();
          break;
        case 3:
          uni.navigateTo({ 
            url: `/pages/bookings/index?venueId=${venue.id}&storeId=${storeId.value}` 
          });
          break;
        case 4:
          handleDeleteVenue(venue);
          break;
      }
    }
  });
};

// 删除场地
const handleDeleteVenue = (venue: Venue) => {
  uni.showModal({
    title: '确认删除',
    content: `确定要删除场地"${venue.name}"吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          // await deleteVenue(venue.id);
          uni.showToast({ title: '删除成功' });
          getVenueList(true);
        } catch (error) {
          uni.showToast({ title: '删除失败', icon: 'none' });
        }
      }
    }
  });
};

// 处理设置
const handleSettings = () => {
  uni.showToast({
    title: '设置功能开发中',
    icon: 'none',
  });
};

// 快捷操作处理函数
const handleBatchOperation = () => {
  uni.showToast({
    title: '批量操作功能开发中',
    icon: 'none'
  });
};

const handleStatusManage = () => {
  uni.showToast({
    title: '状态管理功能开发中',
    icon: 'none'
  });
};

const handleDataExport = () => {
  uni.showToast({
    title: '数据导出功能开发中',
    icon: 'none'
  });
};

// 关闭状态弹窗
const closeStatusModal = () => {
  statusPopup.value?.close();
};

// 切换场地状态
const changeVenueStatus = async (status: number) => {
  if (!currentVenue.value) return;
  
  try {
    await updateVenue(currentVenue.value.id, { status });
    uni.showToast({ title: '状态更新成功' });
    closeStatusModal();
    getVenueList(true);
  } catch (error) {
    uni.showToast({ title: '状态更新失败', icon: 'none' });
  }
};

onLoad((options: any) => {
  if (options.storeId) {
    storeId.value = Number(options.storeId);
    queryParams.store_id = storeId.value;
    getStoreInfo();
  }
});

onShow(() => {
  getVenueList(true);
});
</script>

<style lang="scss" scoped>
.venue-container {
  min-height: 100vh;
  background: linear-gradient(180deg, #1890FF 0%, #F0F9FF 30%);
}

.header {
  padding-top: var(--status-bar-height);
  background: linear-gradient(135deg, #1890FF 0%, #40A9FF 100%);
  
  .header-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 32rpx;
    
    .header-title {
      font-size: 36rpx;
      font-weight: 600;
      color: #fff;
    }
    
    .header-actions {
      display: flex;
      align-items: center;
    }
  }
}

.overview-section {
  margin: -20rpx 32rpx 32rpx;
  
  .overview-card {
    background: #fff;
    border-radius: 16rpx;
    padding: 32rpx;
    box-shadow: 0 4rpx 20rpx rgba(24, 144, 255, 0.1);
    
    .store-info-header {
      margin-bottom: 24rpx;
      text-align: center;
      
      .store-name {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
        display: block;
        margin-bottom: 8rpx;
      }
      
      .store-address {
        font-size: 24rpx;
        color: #666;
      }
    }
    
    .store-stats {
      display: flex;
      
      .overview-item {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        
        .overview-value {
          font-size: 32rpx;
          font-weight: 600;
          color: #1890FF;
          margin-bottom: 8rpx;
        }
        
        .overview-label {
          font-size: 24rpx;
          color: #666;
        }
      }
    }
  }
}

.modules-section {
  padding: 0 32rpx 32rpx;
  
  .modules-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24rpx;
    
    .module-card {
      position: relative;
      background: #fff;
      border-radius: 16rpx;
      padding: 32rpx 24rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
      transition: all 0.3s ease;
      
      &:active {
        transform: scale(0.98);
        box-shadow: 0 1rpx 6rpx rgba(0, 0, 0, 0.1);
      }
      
      .module-icon {
        margin-bottom: 16rpx;
      }
      
      .module-title {
        font-size: 28rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 8rpx;
      }
      
      .module-desc {
        font-size: 24rpx;
        color: #999;
      }
      
      .module-badge {
        position: absolute;
        top: 16rpx;
        right: 16rpx;
        background: #FF4D4F;
        border-radius: 20rpx;
        padding: 4rpx 12rpx;
        
        .badge-text {
          font-size: 20rpx;
          color: #fff;
        }
      }
    }
  }
}

.quick-actions {
  padding: 0 32rpx 32rpx;
  
  .section-title {
    font-size: 28rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 24rpx;
    display: block;
  }
  
  .actions-scroll {
    white-space: nowrap;
    
    .actions-list {
      display: flex;
      gap: 24rpx;
      padding-bottom: 16rpx;
      
      .action-item {
        flex-shrink: 0;
        background: #fff;
        border-radius: 12rpx;
        padding: 24rpx 32rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        min-width: 120rpx;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
        
        .action-icon {
          margin-bottom: 12rpx;
        }
        
        .action-text {
          font-size: 24rpx;
          color: #333;
          white-space: nowrap;
        }
      }
    }
  }
}

.filter-section {
  padding: 0 32rpx 32rpx;
  
  .section-title {
    font-size: 28rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 24rpx;
    display: block;
  }
  
  .filter-card {
    background: #fff;
    border-radius: 16rpx;
    padding: 24rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
    
    .filter-scroll {
      white-space: nowrap;
      
      .filter-tags {
        display: flex;
        gap: 16rpx;
        
        .filter-tag {
          padding: 12rpx 24rpx;
          border-radius: 20rpx;
          background-color: #f5f5f5;
          color: #666;
          font-size: 24rpx;
          white-space: nowrap;
          transition: all 0.3s ease;
          
          &.active {
            background-color: #1890FF;
            color: #fff;
          }
        }
      }
    }
  }
}

.venue-list-section {
  padding: 0 32rpx 32rpx;
  
  .section-title {
    font-size: 28rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 24rpx;
    display: block;
  }
  
  .venue-list-scroll {
    height: 600rpx;
  }
  
  .venue-list {
    .venue-card {
      background: #fff;
      border-radius: 16rpx;
      padding: 24rpx;
      margin-bottom: 16rpx;
      box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
      transition: all 0.3s ease;
      
      &:active {
        transform: scale(0.98);
        box-shadow: 0 1rpx 6rpx rgba(0, 0, 0, 0.1);
      }
      
      .venue-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 16rpx;
        
        .venue-info {
          flex: 1;
          
          .venue-name {
            font-size: 28rpx;
            font-weight: 600;
            color: #333;
            display: block;
            margin-bottom: 8rpx;
          }
          
          .venue-type {
            font-size: 24rpx;
            color: #666;
          }
        }
      }
      
      .venue-details {
        margin-bottom: 16rpx;
        
        .detail-row {
          display: flex;
          align-items: center;
          margin-bottom: 12rpx;
          
          &:last-child {
            margin-bottom: 0;
          }
          
          .detail-item {
            display: flex;
            align-items: center;
            margin-right: 32rpx;
            font-size: 24rpx;
            color: #666;
            
            .detail-text {
              margin-left: 8rpx;
            }
          }
        }
        
        .facilities {
          display: flex;
          align-items: center;
          flex: 1;
          
          .facility-tags {
            display: flex;
            flex-wrap: wrap;
            gap: 8rpx;
            margin-left: 8rpx;
            
            .facility-tag {
              padding: 4rpx 12rpx;
              background-color: #f0f0f0;
              border-radius: 8rpx;
              font-size: 20rpx;
              color: #666;
            }
          }
        }
      }
      
      .venue-actions {
        display: flex;
        gap: 16rpx;
        
        .action-btn {
          flex: 1;
          height: 64rpx;
          border-radius: 12rpx;
          font-size: 24rpx;
          
          &.primary {
            background-color: #1890FF;
            color: #fff;
            
            &:disabled {
              background-color: #ccc;
              color: #999;
            }
          }
          
          &.secondary {
            background-color: #f5f5f5;
            color: #666;
          }
        }
      }
    }
  }
}

.empty-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 400rpx;
  color: #999;

  .empty-text {
    margin: 20rpx 0 40rpx;
    font-size: 28rpx;
  }
  
  .add-venue-btn {
    padding: 20rpx 40rpx;
    background-color: #1890FF;
    color: #fff;
    border-radius: 12rpx;
    font-size: 24rpx;
  }
}

.status-modal {
  background-color: #fff;
  border-radius: 16rpx 16rpx 0 0;
  padding: 40rpx;
  
  .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 40rpx;
    
    .modal-title {
      font-size: 32rpx;
      font-weight: 600;
    }
  }
  
  .status-options {
    display: flex;
    flex-direction: column;
    gap: 24rpx;
    
    .status-option {
      display: flex;
      align-items: center;
      padding: 24rpx;
      border-radius: 12rpx;
      background-color: #f8f9fa;
      
      .status-desc {
        margin-left: 24rpx;
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}
</style>
